// 文章属性编辑模块
define( [
  'jquery',
  'require',
  '../../lib/editData',
  'api',
  '../../lib/utils',
  'combiner',
  'message',
  'constants',
  '../../modules/autoSave',
  'bigwe_utils',
  'h2Api',
  'imgUploader',
  '../../modules/createEditor',
  'artTemplate'
], function( $, require ) {

  var c = require( 'constants' );
  var bu = require( 'bigwe_utils' );
  var editData = require( '../../lib/editData' );
  var BIGWE_API = require( 'api' );
  var EditorAbout = require( '../../lib/utils' );
  var combiner = require( 'combiner' );
  var ShowTitleMessage = require( 'message' );
  var AutoSave = require( '../../modules/autoSave' );
  var iu = require( 'imgUploader' );
  var h2Api = require( 'h2Api' );
  var ue = require( '../../modules/createEditor' );
  var at = require( 'artTemplate' );

  var showTime = ShowTitleMessage.showTime;
  var $articleEditDetails = $( '.article-edit-details' );
  var $ccfc = $( '#choose_cover_from_content' );

  var coverHtml = '{{each list}}<li data-url="{{$value}}"><div class="cover_content" style="background-image: url({{$value}});"><div class="glyphicon glyphicon-ok img_filter"></div></li>{{/each}}';

  $ccfc.on( 'show.bs.modal', function() {
    $( '.spinner', this ).removeClass( 'hide' );
    var imagesArray = [];
    $( 'img', ue.body ).each( function() {
      if ( this.naturalWidth >= 200 && this.naturalHeight >= 200 ) {
        imagesArray.push( $( this ).attr( 'src' ) );
      }
    } );

    var bgArray = ue.body.innerHTML.match( /background-image:(\s*)url\((.*?)\)/g ) || [];
    var imgcheck = 0;
    $.each( bgArray, function( index, item ) {
      item = $.trim( item.replace( /background-image:(\s*)url\(/g, '' ).replace( /\)/g, '' ).replace( /&quot;/g, '' ) );
      if ( item === '' ) {
        bgArray.splice( index, 1 );
      } else {
        bgArray[ index ] = item;
      }
    } );

    bgArray.length ? bgArray.map( function( e ) {

      bu.prepImageRequest( e, function( img ) {
        imgcheck++;
        if ( img.naturalWidth >= 200 && img.naturalHeight >= 200 ) {
          imagesArray.push( e );
        }
        if ( imgcheck === bgArray.length ) {
          fullCoverImages.call( $ccfc, imagesArray );
        }
      } );
    } ) : fullCoverImages.call( $ccfc, imagesArray );

  } ).on( 'click', '.img_list_container li', function() {
    $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
  } ).on( 'click', '.js_choose_ok', function() {
    var url = $( '.img_list_container li.selected', $ccfc ).data( 'url' );
    url && $( '.article-edit-details .cover-input' ).val( url ).trigger( 'change' );
  } );

  function fullCoverImages( imagesArray ) {

    $( '.spinner', this ).addClass( 'hide' );
    var container = $( '.img_list_container', this );

    if ( imagesArray.length ) {
      var html = at.compile( coverHtml )( {
        list: imagesArray
      } );

      container.html( html ).parents( '.has_cover' ).removeClass( 'hide' )
      $( '.no_cover', this ).addClass( 'hide' );
    } else {
      $( '.has_cover', this ).addClass( 'hide' );
      $( '.no_cover', this ).removeClass( 'hide' );
    }
  }

  function coverAppend() {
    if ( $( '#coverImg', combiner.$selector ).length == 0 ) {
      if ( !$( '#art_preview_body', combiner.$selector ).html() ) {
        $( '#art_preview_body', combiner.$selector ).append( EditorAbout.coverHtmlBuild() );
      } else {
        $( '#art_preview_body>*:first-child', combiner.$selector ).before( EditorAbout.coverHtmlBuild() );
      }
    } else {
      $( '#coverImg img', combiner.$selector ).prop( 'src', $( '.cover-input', '.article-edit-details' ).val() );
    }
  }
  var coverUpdata = {
    bindEvent: function() {
      iu.init( 'cover-upload', function( data ) {
        $( '.cover-input', $articleEditDetails ).val( data.image ).trigger( 'change' );
      }, {
        auto_start: true
      } );
      return this;
    },
    // 封面图片显示在正文中
    showCoverCheck: function() {
      $( '.show-cover', $articleEditDetails ).on( 'change', function() {
        if ( this.checked ) {
          editData.setAttrbute( 'show_cover_pic', '1' );
          //coverAppend();
        } else {
          editData.setAttrbute( 'show_cover_pic', '0' );
          //$( '#coverImg', combiner.$selector ).remove();
        }
      } );
      return this;
    }
  }
  coverUpdata.bindEvent().showCoverCheck();

  // 封面图输入框
  $articleEditDetails.on( 'change', '.edit-details>.cover-controll>.reset-mark', function() {
    var thisVal = $.trim( this.value );
    var editIndex = editData.editIndex;
    if ( !$.trim( thisVal ) ) {
      $( '.comb-detail-div>.cover', $( '.graph-manage>ul>li' ).eq( editIndex ) ).css( {
        "background-image": "none"
      } );
      $( '.edit-details>#cover', $articleEditDetails ).css( {
        "background-image": "none"
      } );
    } else {
      $( '.comb-detail-div>.cover', $( '.graph-manage>ul>li' ).eq( editIndex ) ).css( {
        "background-image": "url(" + thisVal + ")"
      } );
      $( '.edit-details>#cover', $articleEditDetails ).css( {
        "background-image": "url(" + thisVal + ")"
      } );
      if ( editData.getAttrbute( 'show_cover_pic' ) === '1' ) {
        coverAppend();
      } else {
        $( '#coverImg', '#art_preview_body' ).remove();
      }
    }
    editData.setAttrbute( 'cdn_url', thisVal );
    editData.setAttrbute( 'isEdit', 1 );
  } ).on( 'keyup change', '#txt_model', function() { // 摘要的输入

    var len = $( this ).val().length;
    $( '.article-abstract>.abs-count>span', $articleEditDetails ).text( len );
    editData.setAttrbute( 'desc', this.value );
    editData.setAttrbute( 'isEdit', 1 );
  } ).on( 'change', '[bw-ui-switch]', function() { // 默认模板开关
    var $this = $( this );
    if ( $this.hasClass( 'active' ) ) {
      $( '.temple_type_container', $this.parents( '.defualt_template' ) ).slideDown();
      gzhstyleHandle();
    } else {
      $( '.temple_type_container', $this.parents( '.defualt_template' ) ).slideUp();
      editData.setAttrbute( 'gzhstyle' );
    }
  } ).on( 'change', '.temple_list input[type="checkbox"]', gzhstyleHandle );

  $( '.defualt_template .moremsg', $articleEditDetails ).popover( $( '.defualt_template .moremsg', $articleEditDetails ).data() )

  function gzhstyleHandle() {
    var templateArray = [];

    $( '.temple_list input[type="checkbox"]', $articleEditDetails ).each( function() {
      if ( $( this )[ 0 ].checked ) {
        templateArray.push( $( this ).val() );
      }
    } );
    if ( !templateArray.length ) {
      templateArray = undefined;
    }
    editData.setAttrbute( 'gzhstyle', templateArray );
  }

  //-------------------------------------------------------
  // 栏目二  编辑器
  var $editColumn2 = $( '.edit-column>.edit-column2' );
  var __editorInnerFunction = {

    textLengthStatistics: function() {
      var $objval = $( this ).val() || $( this ).text();
      //$(this).parent().find('.text-length>span').text($objval.length);
      var txtType = $( this ).attr( 'txt-type' );
      var editIndex = editData.editIndex;
      var maxlength = $( this ).attr( '_maxlength' ) * 1;
      // 标题和作者编辑过了标记
      editData.setAttrbute( 'isEdit', 1 );
      if ( txtType === 'title' ) {
        editData.setAttrbute( 'title', $objval );
        $( this ).prop( 'title', $objval );
        $( '.title', $( '.graph-manage>ul>li' ).eq( editIndex ) ).text( $objval );
        $( this ).parent().find( '.text-length span' ).text( $objval.length );
        // 长度设置
        if ( $objval.length > maxlength ) {
          $( this ).parent().find( '.text-length' ).addClass( 'outRangeLength' );
        } else {
          $( this ).parent().find( '.text-length' ).removeClass( 'outRangeLength' );
        }
      } else if ( txtType === 'author' ) {
        editData.setAttrbute( 'author', $objval );

        var byteLen = bu.getStrChartLen( $objval );
        if ( byteLen % 2 == 1 ) {
          dbLen = ( byteLen + 1 ) / 2;
        } else {
          dbLen = byteLen / 2;
        }
        $( this ).parent().find( '.text-length span' ).text( dbLen );

        if ( dbLen > maxlength ) {
          $( this ).parent().find( '.text-length' ).addClass( 'outRangeLength' );
        } else {
          $( this ).parent().find( '.text-length' ).removeClass( 'outRangeLength' );
        }
      }
    },
    textChangeEvent: function( selector ) {
      function lengthCheck( obj, e ) {
        if ( $( obj ).attr( 'contenteditable' ) ) {
          var maxlength = $( obj ).attr( '_maxlength' ) * 1;
          var thisVal = $( obj ).text();
          e = e || event;
          if ( thisVal.length > maxlength ) {
            $( obj ).text( thisVal.substr( 0, maxlength ) ).parent().find( '.text-length>span' ).text( maxlength );
          }
        }
      }

      function setContentPadding() { //  已废弃
        // 正文在标题换行时，被挡住的问题
        $( '#WxMsgContent' ).show();
        var paddingTop = $( '.title-author-div' ).height() < 95 ? 95 : $( '.title-author-div' ).height();
        $( 'iframe', '#WxMsgContent' ).css( 'paddingTop', paddingTop + 10 + 'px' );
        $( '.CodeMirror.CodeMirror-wrap', '#WxMsgContent' ).css( 'top', paddingTop + 'px' );
      }
      $editColumn2.on( {
          change: __editorInnerFunction.textLengthStatistics,
          keyup: __editorInnerFunction.textLengthStatistics,
          keydown: function( e ) {
            //setContentPadding();
            if ( e.keyCode === 13 ) return false;
            //lengthCheck(this, e);
          },
          focus: function() {
            $( '.edui-toolbar>.toolbarbox-wrap' ).show();
          },
          blur: function() {
            $( '.edui-toolbar>.toolbarbox-wrap' ).hide();
            //__editorInnerFunction.textLengthStatistics(this);
          }
        },
        selector );
      // 修复不可粘贴带有样式的标题
      function textFilter( obj ) {
        $( obj ).html( $( obj ).text() );
      }

      function titleRecommend( title, callback ) {

        function showPrompt() {
          $( '.title-author-div .prompt' ).show();
        }

        function hidePrompt() {
          $( '.title-author-div .prompt' ).hide().find( '.recommend' ).empty();
        }

        function titleHtmlBuild( title ) {
          return '<a href="javascript:;" class="title">' + title + '</a>';
        }

        window.callbackFunction = function( data ) {
          if ( data.length ) {
            $( '.title-author-div .prompt' ).find( '.recommend' ).empty();
            for ( i in data ) {
              if ( data[ i ].title ) {
                $( '.title-author-div .prompt' ).find( '.recommend' ).append( titleHtmlBuild( data[ i ].title ) );
              }
            }
            showPrompt();
          } else {
            hidePrompt()
          }
        }

        if ( title ) {
          $.ajax( {
            type: 'get',
            timeout: 600e3,
            url: h2Api.TITLE_RECOMMEND,
            dataType: 'jsonp',
            data: {
              title: title,
              limit: 10,
            },
            jsonp: 'callback',
            jsonpCallback: 'callbackFunction',
            success: callbackFunction
          } );
        } else {
          hidePrompt();
        }
      }

      function triggerTitleRecommend() {
        titleRecommend( $( this ).val() /*.replace(/\W/g, '')*/ )
      }
      // 下线取标题攻略
      /*$editColumn2.on( {
      		change: function() {},
      		keyup: triggerTitleRecommend,
      		keydown: function( e ) {
      			//$('.prompt').show();
      		},
      		focus: triggerTitleRecommend,
      		blur: function() {
      			//$('.prompt').hide();
      		},
      		paste: function() {
      			//return false;
      		},
      		click: function( e ) {
      			e.stopPropagation();
      		}
      	},
      	'.title-author-div>.article-title-input>.edit-input' );*/

    },
    prompt: function() {

      $( document ).click( function() {
        $( '#WxMsgContent .prompt' ).hide();
      } );

      $( document ).on( 'click', '#WxMsgContent .prompt', function( e ) {
        e.stopPropagation();
      } );

      $( document ).on( 'click', '#WxMsgContent .prompt .recommend .title', function( e ) {
        $( '.title-input', '.title-author-div' ).val( $( this ).text() ).trigger( 'change' );
        $( '#WxMsgContent .prompt' ).hide();
      } );
    }()
  };
  //__urlCapture.clickInit();
  // 标题和作者输入框事件
  __editorInnerFunction.textChangeEvent( '.title-author-div>.article-title-input>.edit-input, .title-author-div>.article-author-input>.edit-input' );
  // '从这里开始写正文'文字点击
  $editColumn2.on( 'click', '.title-author-div>.body-tips', function() {
    ue.focus();
  } );
  // 展开
  $( "#unfold" ).click( function() {
    var $this = this;
    if ( $( '.original-tag-category' ).css( 'display' ) != 'none' ) {
      $( '.original-tag-category' ).slideUp( function() {
        $( '.text', $this ).html( '&nbsp;展开' );
      } );
      $( '.glyphicon', this ).transition( {
        rotate: '0deg'
      } );
    } else {
      $( '.original-tag-category' ).slideDown( function() {
        $( '.text', $this ).html( '&nbsp;收起' );
      } );
      $( '.glyphicon', this ).transition( {
        rotate: '180deg'
      } );
    }
  } );
  var textUrl = {
    check: function() {
      // 勾选原文链接选项
      $( ".srcurl-formwork>.srcurl>input[type='checkbox']" ).change( function() {
        var srcUrl = '';
        if ( $( this )[ 0 ].checked ) {
          //$(this).parent().hide();
          $( '.input-srcurl' ).show( 'normal' );
          srcUrl = $( '.srcurl-formwork>.input-srcurl>input' ).val();
          editData.setAttrbute( 'source_url', srcUrl ).setAttrbute( 'isSource_url', 1 );
        } else {
          $( '.input-srcurl' ).hide( 'normal' );
          editData.setAttrbute( 'source_url' ).setAttrbute( 'isSource_url', 0 );
        }
      } );

      return this;
    },
    uncheck: function() {
      // 取消原文链接选项
      $( '.input-srcurl>.bigwe_default_btn_fff' ).click( function() {
        $( this ).parent().hide();
        $( ".srcurl-formwork>.srcurl" ).show();
        $( ".srcurl-formwork>.srcurl>input[type='checkbox']" )[ 0 ].checked = false;
        editData.setAttrbute( 'source_url' );
        // BETA editData.graphDataDetails[editData.editIndex].source_url = null;
      } );
      return this;
    },
    srcInputChange: function() {
      $( '.srcurl-formwork>.input-srcurl>input' ).change( function() {
        if ( $( ".srcurl-formwork>.srcurl>input[type='checkbox']" )[ 0 ].checked ) {
          editData.setAttrbute( 'source_url', $( this ).val() );
        } else {
          editData.setAttrbute( 'source_url' );
        }
      } );
    }
  };
  var CategoryTage = {
    categoryAndTag: $( '.categoryAndTag-div' ),
    init: function() {
      var $this = this;
      var allRegx = /[^\u4e00-\u9fa5\sa-zA-Z0-9]+/g;
      // 过滤
      function strFilter( str ) {
        return str.replace( allRegx, '' )
      }

      function tagCountCheck( obj ) {
        if ( $( '.tage-content .content>div', $this.categoryAndTag ).length >= 5 ) {
          ShowTitleMessage.showWarning( "标签最多只能有五个:-(", showTime );
          $( obj ).val( '' );
          return false;
        }
        return true;
      }
      var maxlength = c.tagsMaxCharLenth,
        minlength = 2;
      $( '.input-tage .tag-input' ).on( 'keyup', function( e ) {
        e = e || event;
        var thisVal = $( this ).val();
        var regx = /,/;
        if ( !$.trim( thisVal ) ) {
          $( this ).val( '' );
        }
        if ( thisVal.length > 0 ) {
          if ( !tagCountCheck( this ) ) return;
          var lastStr = thisVal.substr( thisVal.length - 1 );
          if ( regx.test( lastStr ) || e.keyCode == 188 || e.keyCode == 13 /*32*/ ) {
            if ( bu.strlen( thisVal ) < 2 ) {
              $( this ).trigger( 'focus' );
              ShowTitleMessage.showWarning( "标签至少为一个汉字或两个字符哦", showTime );
            } else {
              var cleanStr = strFilter( $.trim( thisVal ) ).cutStringByte( maxlength );
              if ( cleanStr ) {
                EditorAbout.tageChange( cleanStr );
              } else {
                $( this ).val( '' );
              }
            }
          }
        }

      } ).on( 'blur', function() {
        var thisVal = $.trim( $( this ).val() );
        if ( bu.strlen( thisVal ) == 1 ) {
          $( this ).trigger( 'focus' );
          ShowTitleMessage.showWarning( "标签至少为一个汉字或两个字符哦", showTime );
        } else {
          var cleanStr = strFilter( $.trim( thisVal ) ).cutStringByte( maxlength );

          if ( !$.trim( thisVal ) || !cleanStr ) {
            $( this ).val( '' );
          } else {
            if ( !tagCountCheck( this ) ) return;
            EditorAbout.tageChange( cleanStr );
          }

          if ( $( '.tage-content .content>div', $this.categoryAndTag ).length > 0 ) {
            $( '.input-tage>.spa_gray', $this.categoryAndTag ).hide();
          } else {
            $( '.input-tage>.spa_gray', $this.categoryAndTag ).show();
          }
        }

      } ).on( 'focus', function() {
        $( '.input-tage>.spa_gray' ).hide();
      } ).on( 'keydown', function( e ) {
        var thisVal = $.trim( this.value );
        e = e || event;
        if ( bu.strlen( thisVal ) >= 20 && e.keyCode != 8 // 删除
          && e.keyCode != 46 // delete
          && e.keyCode != 37 // 方向左键
          && e.keyCode != 39 // 方向右键
        ) {
          return false;
        }
      } );
      $( '.tage-content .content', this.categoryAndTag ).on( 'click', 'div', function( e ) {
        e.stopPropagation();
        $( this ).remove();
        EditorAbout.tageChange();
      } );
      $( '.input-tage', this.categoryAndTag ).click( function() {
        $( 'input[type="text"]', this ).trigger( 'focus' );
      } );
    }
  };
  CategoryTage.init();
  textUrl.check().uncheck().srcInputChange();

  // 
  $( document ).on( 'click', '#WxMsgContent .prompt .foot a', function() {
    $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
    $( '.body>div', $( this ).parent().parent() ).hide().eq( $( this ).index() == 2 ? 1 : $( this ).index() ).show();
  } ).on( 'click', '.autosave>.draft-text, .js_draft_fullin', function() { // 调出草稿
    if ( $( this ).hasClass( 'disabled' ) ) {
      ShowTitleMessage.showWarning( '当前还没有草稿', showTime );
    } else {
      AutoSave.fullDataToPage();
    }
  } );
} );